package com.aaron.book.thinkinginjava.c21.p656;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 *
 * @author liurong
 * @date 2021/7/9 14:18
 */
public class C21E2 {
    public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            new Thread(new FibonacciGenerator()).start();
        }

    }
}

class FibonacciGenerator implements Runnable {

    private static int size = 50;

    private static int taskCount = 0;

    private final int id = taskCount++;

    private List<Integer> resultList = new ArrayList<Integer>();

    private int[] inits = {1, 1};

    public FibonacciGenerator() {
        Arrays.stream(inits).forEach(t -> resultList.add(t));
    }

    public FibonacciGenerator(int resultSize, List<Integer> resultList) {
        size = resultSize;
        this.resultList = resultList;
        Arrays.stream(inits).forEach(t -> resultList.add(t));
    }

    @Override
    public void run() {

        while (size >= 2) {
            generate();
        }

    }

    private synchronized void generate() {
        if (size-- > 2) {
            int currentSize = resultList.size();
            resultList.add(resultList.get(currentSize-1) + resultList.get(currentSize - 2));
        } else {
            resultList.forEach(t->System.out.print(t+","));
            System.out.println(resultList.size());
        }
    }

}
